package kdiapo;

import Model.*;
import View.*;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;

import javax.net.ssl.SSLContext;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.poi.hslf.model.Background;
import org.apache.poi.hslf.model.Picture;
import org.apache.poi.hslf.model.Shape;
import org.apache.poi.hslf.model.ShapeTypes;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.PictureData;
//import org.jvnet.substance.skin.SubstanceBusinessBlackSteelLookAndFeel;
import org.xml.sax.SAXException;

import com.connectina.swing.fontchooser.JFontChooser;

//import org.jvnet.substance.skin.SubstanceOfficeBlue2007LookAndFeel;

/** Main Frame : View and Controler */
public class CreationFrame extends JFrame  implements Observer{
	
	/**-----------------------------------------------------------------------------------*/
	/** Variables declaration ------------------------------------------------------------*/ 
	/**-----------------------------------------------------------------------------------*/
    private JButton btnImage;
    private JButton btnVideo;
    private JButton btnNew;
    private JButton btnAddSlide;
    private JButton btnOpen;
    private JButton btnSave;
    private JButton btnText;
    private JButton btnBackground;
    private JButton btnFont;
    private JButton btnFontColor;
    
    private JMenu jMenu1;
    private JMenu jMenu2;
    private JMenu jMenu3;
    private JMenu jMenu4;
    private JMenuBar jMenuBar1;
    
    private JMenuItem menuOpen;
    private JMenuItem menuNew;
    private JMenuItem menuSave;
    private JMenuItem menuSaveAs;
    private JMenuItem exportToPPT;
    private JMenuItem importToPPT;
    private JMenuItem menuNewSlide;
    private JMenuItem menuInsertText;
    private JMenuItem menuInsertImage;
    private JMenuItem menuInsertVideo;
    private JMenuItem menuSlideShow;
    private JMenuItem menuHelpContents;
    private JMenuItem menuHelp;
    private SlideShow slideShowFrame;
    
    private JPanel jPanel1;
    private JPanel jPanel5;
    private JLabel lbSlideShow;
  
    private JScrollPane jScrollPane1;
    private Box vbox;
    
    private JTabbedPane jTabbedPane1;
    private JScrollPane jScrollPane2;
    private JLabel lbPicture;
    private JLabel lbVideo;
    private JLabel lbText;
    private JPanel jPanel2;
    private GridBagLayout glayoutPicture;
    private GridBagConstraints cPicture;
    private JPanel jPanel3;
    private GridBagLayout glayoutVideo;
    private GridBagConstraints cVideo;
    private JPanel jPanel4;
    private GridBagLayout glayoutText;
    private GridBagConstraints cText;
    
    
    private JToolBar jToolBar1;
    private JToolBar jToolBar2;
    private JToolBar jToolBar3;
    private JToolBar jToolBarStyle;
    private JPanel pContentDiapo;
    private JScrollPane scrollContent;
    
    private JPanel currentSlide;
    
    private JSplitPane jSplitePane1;
    private JSplitPane splitOverview;
    private JPanel jPanel6;

    //Model of the current project
    private ListSlideModel model;
    //Objet permettant le redimenssionnement des objets
    private Resizable resizer;
    
    private int oldCurrentSlide;
    private int oldNbSlide;
    
    private boolean isSaved = false;
    private boolean isModified = false;
    private File fFile = null;
    
    private CreationFrame myFrame;
    
    /**-----------------------------------------------------------------------------------*/
    /** Constructor ----------------------------------------------------------------------*/
    /**-----------------------------------------------------------------------------------*/
    public CreationFrame() {
    	//Init of graphics components
        initComponents();
        
        myFrame = this;
        
        this.setExtendedState(Frame.MAXIMIZED_BOTH);
        ImageIcon ic=new ImageIcon(Main.class.getResource("/open.png"));
        ImageIcon in=new ImageIcon(Main.class.getResource("/new.png"));
        ImageIcon is=new ImageIcon(Main.class.getResource("/save.png"));
        ImageIcon it=new ImageIcon(Main.class.getResource("/text.png"));
        ImageIcon im=new ImageIcon(Main.class.getResource("/image.png"));
        ImageIcon iv=new ImageIcon(Main.class.getResource("/video.png"));
        ImageIcon ia=new ImageIcon(Main.class.getResource("/add.png"));
        ImageIcon backgroundIcon = new ImageIcon(Main.class.getResource("/background_color.png"));
        ImageIcon fontIcon = new ImageIcon(Main.class.getResource("/font.png"));
        ImageIcon fontColorIcon = new ImageIcon(Main.class.getResource("/text_color.png"));
        
        btnOpen.setIcon(getIcon(ic));
        btnOpen.setToolTipText("Open an existing project");
        btnNew.setIcon(getIcon(in));
        btnNew.setToolTipText("New project");
        btnSave.setIcon(getIcon(is));
        btnSave.setToolTipText("Save");
        btnText.setIcon(getIcon(it));
        btnText.setToolTipText("Insert text");
        btnImage.setIcon(getIcon(im));
        btnImage.setToolTipText("Insert an image");
        btnVideo.setIcon(getIcon(iv));
        btnVideo.setToolTipText("Insert a video");
        btnAddSlide.setIcon(getIcon(ia));
        btnAddSlide.setToolTipText("Add a new slide");
        btnBackground.setIcon(getIcon(backgroundIcon));
        btnBackground.setToolTipText("Change background color");
        btnFont.setIcon(getIcon(fontIcon));
        btnFont.setToolTipText("Change font");
        btnFontColor.setIcon(getIcon(fontColorIcon));
        btnFontColor.setToolTipText("Change font color");
        
    }
    /**-----------------------------------------------------------------------------------*/
    /**-----------------------------------------------------------------------------------*/

    
    /**-----------------------------------------------------------------------------------*/
    /**Methods for insertion of elements--------------------------------------------------*/
    /**-----------------------------------------------------------------------------------*/
    private void insertText(){
    	//Creation of the element in the model
        int numElement = model.addText();
        
        System.out.println("Numero de l'element :"+numElement);
    	
        //Creation of the element in the view
        TextView area = new TextView(this,numElement,currentSlide.getBackground(),
        		model.getListSlide().get(model.getCurrentSlide()-1).getSlideFontColor(),
        		model.getListSlide().get(model.getCurrentSlide()-1).getSlideFont());
	      
        //Add the element to currentSlide and update the snapeShot
        this.addElementToCurrentSlide(area,numElement);
    }

    private void insertImage(String filename){
    	int numElement = model.addImage(filename);
    	
    	ImageView area = new ImageView(this,numElement,filename); 
     
    	//Add the element to currentSlide and update the snapeShot
        this.addElementToCurrentSlide(area,numElement);
    }
    
    private void insertVideo(File f){
    	int numElement = model.addVideo(f.getAbsolutePath());
    	
    	VideoView area = new VideoView(this,numElement,f); 
     
    	//Add the element to currentSlide and update the snapeShot
        this.addElementToCurrentSlide(area,numElement);
    	
    }
    
    private void addElementToCurrentSlide(ElementView area, int numElement){
    	 //insertion of the element in the view
    	TextView TxtElt;
    	ImageView ImElt;
    	VideoView VidElt;
    	if(area instanceof TextView){
    		TxtElt = (TextView)area;
    		currentSlide.add(TxtElt.getResizer(),numElement);
    	}
    	if(area instanceof ImageView){
    		ImElt = (ImageView)area;
    		currentSlide.add(ImElt.getResizer(),numElement);
    	}
    	if(area instanceof VideoView){
    		VidElt = (VideoView)area;
    		currentSlide.add(VidElt.getResizer(),numElement);
    	}
    		
	    currentSlide.revalidate();
	    currentSlide.repaint();
	    
	    SnapShotView old = (SnapShotView) jPanel1.getComponent(model.getCurrentSlide()-1);
		old.updateSnapShot(currentSlide);

		jPanel1.revalidate();
		jPanel1.repaint();
    }
    
    private Icon getIcon(ImageIcon ic){
        Image img = ic.getImage() ;
        Image newimg = img.getScaledInstance( 30, 25,  java.awt.Image.SCALE_SMOOTH ) ;
        Icon icon = new ImageIcon( newimg );
        return icon;
    }
    /**-----------------------------------------------------------------------------------*/
    /**-----------------------------------------------------------------------------------*/

    /**-----------------------------------------------------------------------------------*/
    /**Initialization of components----------------------------------------------------------------*/
    /**-----------------------------------------------------------------------------------*/
    private void initComponents() {

    	//Initialisation of the model
    	model = new ListSlideModel();
    	model.addObserver(this);
    	
    	/*ImageIcon im = new ImageIcon("src/images/LogoKDIAPO.png");
    	this.setIconImage(im.getImage());*/
    	
    	//Creation of the components
        jToolBar1 = new JToolBar();
        jToolBar3 = new JToolBar();
        btnOpen = new JButton();
        btnNew = new JButton();
        btnSave = new JButton();
        btnAddSlide = new JButton();
        jPanel5 = new JPanel();
        lbSlideShow = new JLabel("No current project");
       
        jScrollPane2 = new JScrollPane();
        jTabbedPane1 = new JTabbedPane();
        jPanel2 = new JPanel();
        jPanel3 = new JPanel();
        jPanel4 = new JPanel();
        pContentDiapo = new JPanel();
        scrollContent = new JScrollPane(pContentDiapo);
        jToolBar2 = new JToolBar();
        btnText = new JButton();
        btnImage = new JButton();
        btnVideo = new JButton();
        jToolBarStyle = new JToolBar();
        btnBackground = new JButton();
        btnFont = new JButton();
        btnFontColor = new JButton();
        
        jMenuBar1 = new JMenuBar();
        jMenu1 = new JMenu();
        jMenu2 = new JMenu();
        jMenu3 = new JMenu();
        jMenu4 = new JMenu();
       
        jPanel1 = new JPanel();
        
        jSplitePane1 = new JSplitPane();
        jPanel6 = new JPanel();
        jScrollPane1 = new JScrollPane();   
        
        splitOverview= new JSplitPane(JSplitPane.VERTICAL_SPLIT);
             
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        scrollContent.setViewportView(pContentDiapo);
        jToolBar1.setRollover(true);

        btnOpen.setFocusable(false);
        btnOpen.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnOpen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenActionPerformed(evt);
            }           
        
        });
        jToolBar1.add(btnOpen);

        btnNew.setFocusable(false);
        btnNew.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });
        jToolBar1.add(btnNew);

        btnSave.setFocusable(false);
        btnSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });
        jToolBar1.add(btnSave);

        jToolBar3.setEnabled(false);

        jToolBar1.setRollover(true);
        
        jToolBar3.add(jToolBar1);

        jToolBar2.setRollover(true);
        
        jToolBar3.add(jToolBar2);
        
        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar3, javax.swing.GroupLayout.DEFAULT_SIZE, 1653, Short.MAX_VALUE)
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar3, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
      

        jTabbedPane1.addTab("Picture", jPanel2);
       
        jScrollPane1.setViewportView(jPanel1);
    
        glayoutVideo = new GridBagLayout();
        jPanel3.setLayout(glayoutVideo);
        
        cVideo = new GridBagConstraints();
        cVideo.fill = GridBagConstraints.NONE;
        
        glayoutPicture = new GridBagLayout();
        jPanel2.setLayout(glayoutPicture);
        
        cPicture = new GridBagConstraints();
        cPicture.fill = GridBagConstraints.NONE;
        
        glayoutText = new GridBagLayout();
        jPanel4.setLayout(glayoutText);
        
        cText = new GridBagConstraints();
        cText.fill = GridBagConstraints.NONE;
        
        jTabbedPane1.addTab("Video", jPanel3);
        
        jTabbedPane1.addTab("Text", jPanel4);

        jScrollPane2.setViewportView(jTabbedPane1);


        jToolBar2.setRollover(true);
        
        btnAddSlide.setFocusable(false);
        btnAddSlide.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAddSlide.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAddSlide.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	btnAddSlideActionPerformed(evt);
            }
        });
        jToolBar2.add(btnAddSlide);
        
        btnText.setFocusable(false);
        btnText.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnText.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTextActionPerformed(evt);
            }
        });
        jToolBar2.add(btnText);

        btnImage.setFocusable(false);
        btnImage.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnImage.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImageActionPerformed(evt);
            }
        });
        jToolBar2.add(btnImage);
        
        btnVideo.setFocusable(false);
        btnVideo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnVideo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnVideo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	btnVideoActionPerformed(evt);  

            }
        });
        jToolBar2.add(btnVideo);

        jToolBarStyle.setRollover(true);
        btnBackground.setFocusable(false);
        btnBackground.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnBackground.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnBackground.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	Color initialBackground = currentSlide.getBackground();
                Color background = JColorChooser.showDialog(null, "Change Slide Background",initialBackground);
                if (background != null) {
                	currentSlide.setBackground(background);
                	model.setSlideBackgroundColor(currentSlide.getBackground());
                	
                	Component[] components = currentSlide.getComponents();
                    for (Component c : components) {                    	
                    	if (c instanceof Resizable){
                    		Component comp = ((Resizable) c).getComp();
                    		if (comp.getClass() == JTextPane.class){
                    			comp.setBackground(background);
                    		}
                    	}
                    }
                }
            }
        });
        jToolBarStyle.add(btnBackground);
        btnFont.setFocusable(false);
        btnFont.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnFont.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnFont.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	Font initialFont = new Font("Arial", Font.PLAIN, 12);
            	Font font = JFontChooser.showDialog(myFrame, initialFont);
            	if (font != null){
            		Component[] components = currentSlide.getComponents();
                    for (Component c : components) {                    	
                    	if (c instanceof Resizable){
                    		Component comp = ((Resizable) c).getComp();
                    		if (comp.getClass() == JTextPane.class){
                    			comp.setFont(font);                    			
                    		}
                    		
                    	}
                    }
                    model.getListSlide().get(model.getCurrentSlide()-1).setSlideFont(font);
            	}            	
            }
        });
        jToolBarStyle.add(btnFont);
        btnFontColor.setFocusable(false);
        btnFontColor.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnFontColor.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnFontColor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	Color initialBackground = currentSlide.getBackground();
                Color fontColor = JColorChooser.showDialog(null, "Change Font Color",initialBackground);
            	if (fontColor != null){
            		Component[] components = currentSlide.getComponents();
                    for (Component c : components) {                    	
                    	if (c instanceof Resizable){
                    		Component comp = ((Resizable) c).getComp();
                    		if (comp.getClass() == JTextPane.class){
                    			comp.setForeground(fontColor);
                    		}
                    	}
                    }
                    model.getListSlide().get(model.getCurrentSlide()-1).setSlideFontColor(fontColor);
            	}
            }
        });
        jToolBarStyle.add(btnFontColor);
        jToolBar3.add(jToolBarStyle);
        jSplitePane1.setRightComponent(scrollContent);
        jSplitePane1.setLeftComponent(jPanel6);
        // System.out.println("Taille="+jPanel6.getPreferredSize().getWidth());
        jSplitePane1.setDividerLocation(250);
        
        splitOverview.setLeftComponent(jScrollPane1);
        splitOverview.setRightComponent(jScrollPane2);
        splitOverview.setDividerLocation(260);
         
        
        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(splitOverview)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addComponent(splitOverview))
        );
        
        
        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        jMenu3.setText("Window");
        jMenuBar1.add(jMenu3);
        
        menuSlideShow = new JMenuItem("SlideShow");   
        menuSlideShow.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, ActionEvent.CTRL_MASK));
        
        menuNew = new JMenuItem("New project");
        menuOpen = new JMenuItem("Open an existing project");
        menuSave = new JMenuItem("Save");
        menuSaveAs = new JMenuItem("Save as");
        exportToPPT=new JMenuItem("Export to ppt");
        importToPPT=new JMenuItem("Import ppt file");
        menuNewSlide = new JMenuItem("New slide");
        menuInsertText = new JMenuItem("Insert text");
        menuInsertImage = new JMenuItem("Insert an image");
        menuInsertVideo = new JMenuItem("Insert a video");
        menuHelpContents = new JMenuItem("Help contents");
        menuHelp = new JMenuItem("About");
        
        menuNew.addActionListener(new Action());
        menuOpen.addActionListener(new Action());
        menuSave.addActionListener(new Action());
        menuSaveAs.addActionListener(new Action());
        menuNewSlide.addActionListener(new Action());
        exportToPPT.addActionListener(new Action());
        importToPPT.addActionListener(new Action());
        menuInsertText.addActionListener(new Action());
        menuInsertImage.addActionListener(new Action());
        menuInsertVideo.addActionListener(new Action());
        menuSlideShow.addActionListener(new Action());
        menuHelpContents.addActionListener(new Action());
        menuHelp.addActionListener(new Action());
        
        jMenu1.add(menuNew);
        jMenu1.add(menuOpen);
        jMenu1.add(menuSave);
        jMenu1.add(menuSaveAs);
        jMenu1.add(importToPPT);
        jMenu1.add(exportToPPT);
        jMenu2.add(menuNewSlide);
        jMenu2.add(menuInsertText);
        jMenu2.add(menuInsertImage);
        jMenu2.add(menuInsertVideo);
        jMenu4.add(menuHelpContents);
        jMenu4.add(menuHelp);
        
        
        jMenu3.add(menuSlideShow);

        jMenu4.setText("Help");
        jMenuBar1.add(jMenu4);

        setJMenuBar(jMenuBar1);
        
        jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.Y_AXIS));
       
        
        
        //Put enable some components at the beginning
        btnSave.setEnabled(false);
        btnAddSlide.setEnabled(false);
        btnImage.setEnabled(false);
        btnText.setEnabled(false);
        btnVideo.setEnabled(false);
        btnBackground.setEnabled(false);
        btnFont.setEnabled(false);
        btnFontColor.setEnabled(false);
        menuSave.setEnabled(false);
        menuSaveAs.setEnabled(false);
        menuNewSlide.setEnabled(false);
        exportToPPT.setEnabled(false);
        menuInsertText.setEnabled(false);
        menuInsertImage.setEnabled(false);
        menuInsertVideo.setEnabled(false);
                
       
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jSplitePane1,  javax.swing.GroupLayout.DEFAULT_SIZE, 1653, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSplitePane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1141,Short.MAX_VALUE)
                .addContainerGap(580, Short.MAX_VALUE))
        );
        
       
        pack();
    }
    /**-----------------------------------------------------------------------------------*/
    /**-----------------------------------------------------------------------------------*/
    
    /**-----------------------------------------------------------------------------------*/
    /**Actions of buttons--------------------------------------------------------------*/
    /**-----------------------------------------------------------------------------------*/
    private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {
    	openExistingProject();    	
    }
    
    private void openExistingProject(){
    	if(verifyProjectSaved()){
	    	JFileChooser file = new JFileChooser();
		    FileFilter imagesFilter = new FileNameExtensionFilter("Fichiers XML", "xml");
		    file.setFileFilter(imagesFilter);
		    file.setDialogTitle("Ouvrir un projet Kdiapo");
		         
		    int result = file.showOpenDialog(this);
		    if (result == JFileChooser.CANCEL_OPTION) {
		        return;
		    } else if (result == JFileChooser.APPROVE_OPTION) {
		        File f = file.getSelectedFile();
		        if(f.getAbsolutePath().indexOf("xml")>0){
		        	try {
		        		KdiapoFacility.mainFrame = this;
		                KdiapoFacility.parse(f.getAbsolutePath());
		                this.setIsModified(false);
		                this.fFile = f;
		                this.isSaved = true;
		            } catch (FileNotFoundException e) {
		                e.printStackTrace();
		            } catch (SAXException e) {
		                e.printStackTrace();
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        }
				else if(f.getAbsolutePath().indexOf("ppt")>0){
					FileInputStream is;
					try {
						is = new FileInputStream(f.getAbsolutePath());
						org.apache.poi.hslf.usermodel.SlideShow ppt = new org.apache.poi.hslf.usermodel.SlideShow(is);
						is.close();
						org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides();
						model=new ListSlideModel();
						model.setNbSlide(slide.length);
						model.setCurrentSlide(slide.length);
						model.setNameProject(ppt.toString());
						ArrayList<SlideContent> list=new ArrayList<SlideContent>();
						int cpt=1;
						for (org.apache.poi.hslf.model.Slide sl: slide){
							SlideContent s=new SlideContent();
							s.setSlideBackgroundColor(sl.getBackground().getFill().getBackgroundColor());
							s.setNumSlide(cpt);
							ArrayList<ElementSlide> elt=new ArrayList<ElementSlide>();
							TextRun[] textRuns = sl.getTextRuns();
							int i=0;
							for(Shape sh:sl.getShapes()){
								if(sh.getShapeType()==ShapeTypes.Rectangle){
									TextElement te=new TextElement();
									te.setTextValue(textRuns[i].getText());
									Rectangle r=sh.getAnchor();
									te.setPosX((int)r.getX());
									te.setPosY((int)r.getY());
									te.setHeight((int)r.getHeight());
									te.setWidth((int)r.getWidth());
									elt.add(te);
									TextRun tr=sl.getTextRuns()[0];
									//Font fnt=new Font(tr.getRichTextRuns()[0].getFontName(),0,tr.getRichTextRuns()[0].getFontSize());
									int type = 0;
									if(tr.getRichTextRuns()[0].isBold())
										type=Font.BOLD;
									if(tr.getRichTextRuns()[0].isItalic())
										type+=Font.ITALIC;

									//if(tr.getRichTextRuns()[0].is);
									Font fnt=new Font(tr.getRichTextRuns()[0].getFontName(),type,tr.getRichTextRuns()[0].getFontSize());
									System.out.println(type==Font.ITALIC);
									s.setSlideFont(fnt);
									s.setSlideFontColor(tr.getRichTextRuns()[0].getFontColor());
									te.setNumElement(i);

								}
								else if(sh.getShapeName().equals("PictureFrame")){
									ImageElement ie=new ImageElement();
									Picture pic=(Picture) sh;
									PictureData pd=pic.getPictureData();
									byte[] data = pd.getData();
									int typ = pd.getType();
									File in = null;
									if (typ == Picture.JPEG){
										in=new File("slide0_"+cpt+"_"+(i+1)+".jpg");
										System.out.println(in.getAbsolutePath());

									} else if (typ == Picture.PNG){
										//FileInputStream in = null;
										in=new File("slide0_"+cpt+"_"+(i+1)+".png");
										System.out.println(in.getAbsolutePath());
									}
									Rectangle r=sh.getAnchor();
									ie.setPath(in.getAbsolutePath());
									ie.setHeight((int)r.getHeight());
									ie.setWidth((int)r.getWidth());
									ie.setPosX((int)r.getX());
									ie.setPosY((int)r.getY());
									ie.setNumElement(i);
									elt.add(ie);

								}
								i++;
							}
							s.setListElements(elt);
							list.add(s);
							cpt++;
						}
						model.setListSlide(list);



					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					setNewModel(model) ; 
				}
		    }
    	}

    }

    private boolean verifyProjectSaved(){
    	if(jPanel1.getComponentCount()!=0){
    		//If current project has never been saved
    		if(fFile==null){
    			int response = JOptionPane.showConfirmDialog(null, "Save current project ?",
    					"Confirm Overwrite",JOptionPane.YES_NO_CANCEL_OPTION,
    					JOptionPane.CANCEL_OPTION);
    			if(response == JOptionPane.CANCEL_OPTION){
    	    		return false;
    	    	}else if(response==JOptionPane.YES_OPTION){
    	    		this.saveAs();
    	    	}
    		}else{
    			//If project has been modified
    			if(this.isModified==true){
    				int response = JOptionPane.showConfirmDialog(null, "Save current project ?",
        					"Confirm Overwrite",JOptionPane.YES_NO_CANCEL_OPTION,
        					JOptionPane.CANCEL_OPTION);
        			if(response == JOptionPane.CANCEL_OPTION){
        	    		return false;
        	    	}else if(response==JOptionPane.YES_OPTION){
        	    		this.setIsModified(false);
        	    		writeFile(fFile, model.generateXMLProject());
        	    		return true;
        	    	}else
        	    		return true;
    			}
    		}
    	}
    	return true;
    }
    private boolean openNewProject(){
    	if(verifyProjectSaved()){

	    	//Ask for project name
	    	String projectName = JOptionPane.showInputDialog(null,"Enter the name of the new project :", "New project", JOptionPane.QUESTION_MESSAGE);
	    	//System.out.println("Nom du projet : "+projectName);
	    	
	    	//If name is not null, we create the project
	    	if(projectName!=null && !projectName.equals("")){
	    		//Update model
	    			//project name
	    			model = new ListSlideModel();
	    			model.addObserver(this);
	    			
	    			model.setNameProject(projectName);
	    			
	    			
	    			oldCurrentSlide=1;
	    			oldNbSlide = 1;
	    			
	    			//Add Slide
	    			model.addSlide();
	    			
	    			
	    		//Update View
	    			//Reactivation of buttons
	    			this.enableAllBtn();
	    			
	    			//Remove all components of pContentDiapo
	    			pContentDiapo.removeAll();
	    			
	    			//Creation of current Slide
	    			currentSlide = new JPanel();
	    			
	    			currentSlide.setBackground(model.getListSlide().get(model.getCurrentSlide()-1).getSlideBackgroundColor());
	    			pContentDiapo.add(currentSlide);
	    			currentSlide.setBounds(100,0,800,580);
	    			
	    			//set Layout for insertion of elements
	    			setLayoutForSlide(currentSlide);
	    			
	    			//set title to application
	    			this.setTitle(projectName);
	    			
	    			//remove components from JPanel1
	    			jPanel1.removeAll();
	    			
	    			//Creation of snapshot of currentSlide 
	    			SnapShotView sp = new SnapShotView(this,model.getCurrentSlide(),currentSlide);
	    			//jPanel1.add(sp,0);
	    			jPanel1.add(sp);
	    					
	    			//update jPanel1 that show the screenshot
	            	jPanel1.revalidate();
	            	jPanel1.repaint();
	            	
	            	prepareChoiceGest(jPanel2,"Picture");
	            	prepareChoiceGest(jPanel3,"Video");
	            	prepareChoiceGest(jPanel4,"Text");
	            	
	            	
	            	return true;
	    		
	    	}
    	}
    	return false;
    }
    
    private void btnAddSlideActionPerformed(java.awt.event.ActionEvent evt){
    	newSlide();
    }
    
    public void newSlide(){
    	//Add a slide to model
    	model.addSlide();
    	
    	//update jPanel1 for screenshot
    	SnapShotView sp = new SnapShotView(this,model.getCurrentSlide(), currentSlide);
    	//jPanel1.add(sp,model.getCurrentSlide()-1);
 	
    	jPanel1.add(sp);
    	
    	jPanel1.revalidate();
    	jPanel1.repaint();
    	
    }
    
    private void btnTextActionPerformed(java.awt.event.ActionEvent evt) {
        insertText();
    }

    private void btnImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImageActionPerformed
        
    	insertImage();
    }
    
    public void insertImage(){
    	JFileChooser file = new JFileChooser();
        FileFilter imagesFilter = new FileNameExtensionFilter("Images", "bmp", "gif", "jpg", "jpeg", "png");
        file.setFileFilter(imagesFilter);
		file.setDialogTitle("Insérer une image");
		int result = file.showOpenDialog(this);

		if (result == JFileChooser.CANCEL_OPTION) {
			return;
		} else if (result == JFileChooser.APPROVE_OPTION) {
			File f = file.getSelectedFile();
            insertImage(f.getAbsolutePath());
		}
    }
    
    private void btnVideoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImageActionPerformed
    	insertVideo();
    }
    
    public void insertVideo(){
    	JFileChooser file = new JFileChooser();
        FileFilter videoFilter = new FileNameExtensionFilter("Video", "avi");
        file.setFileFilter(videoFilter);
		file.setDialogTitle("Insert a video");
		int result = file.showOpenDialog(this);

		if (result == JFileChooser.CANCEL_OPTION) {
			return;
		} else if (result == JFileChooser.APPROVE_OPTION) {
			File f = file.getSelectedFile();
            insertVideo(f);
		}
    }
    private void prepareChoiceGest(JPanel p, String type){
    	p.removeAll();
    	
    	Iterator<String> itr = null;
    	GridBagConstraints c = null;
    	Iterator<Gesture> itrGest = null;
    	
    	//Prepare choice gest 
    	if(type.equals("Video")){
    		itr = model.getListGestureVideo().getListRoles().iterator();
    		itrGest = model.getListGestureVideo().getListGest().iterator();
    		c = cVideo;
    
    	}
    	else if(type.equals("Picture")){
    		itr = model.getListGesturePicture().getListRoles().iterator();
    		itrGest = model.getListGesturePicture().getListGest().iterator();
    		c=cPicture;
    	}
    	else if(type.equals("Text")){
    		itr = model.getListGestureText().getListRoles().iterator();
    		itrGest = model.getListGestureText().getListGest().iterator();
    		c=cText;
    	}
    	
    	int x=0;
        int y=0;
        int i=0;
	    while (itr.hasNext()) {
	    	x=0;
	    	
	    	ListGesture lg = null;
	    	if(type.equals("Video")){
	    		lg = model.getListGestureVideo();
	    	}
	    	else if(type.equals("Picture")){
	    		lg = model.getListGesturePicture();
	    	}
	    	else if(type.equals("Text")){
	    		lg = model.getListGestureText();
	    	}
	    	
	    	itrGest = lg.getListGest().iterator();
	    	
	    	String roleName = itr.next();
	    	JLabel lb = new JLabel("<html><u>"+lg.getListDescription().get(i)+"</u></html>");
	    	lb.setFont(new Font(lb.getFont().toString(),Font.PLAIN,12));
	    	c.gridwidth = 2;
	        c.gridheight = 1;
	        c.gridx=x;
	        c.gridy=y;
	        
	        p.add(lb,c);
	        
	        y++;
	        while (itrGest.hasNext()) {
	        	Gesture g = itrGest.next();
	        	
	        	if(g.getRole().equals(roleName)){	        	
		        	GestureView gv = new GestureView(g.getPathIcon(),g.getNumGest(),g.getRole(),g.isSelected(),type,this);
		        	gv.setToolTipText(g.getGestDescription());
		        	
		        	if(!g.isSelected()){
		        		gv.setBorder(BorderFactory.createEmptyBorder());
		        	}
		        	
		        	cVideo.gridwidth = 1;
			        cVideo.gridheight = 1;
			        cVideo.gridx=x;
			        cVideo.gridy=y;
			        
			        p.add(gv,cVideo);
			        
			        x++;
	        	}
	        }
	        y++;
	        
	        i++;
	    }
	   
    }
    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
    	//System.out.println(model.generateXMLProject());
	
    	save();
    }
    
    public void save(){
    	//Si fichier d�j� ouvert
    	if(isSaved){
    		this.setIsModified(false);
    		writeFile(fFile, model.generateXMLProject());
    	}else{
    		this.saveAs();
    	}
    }
    
    public static boolean writeFile(File file, String dataString){
    	
    	try {
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
			out.print(dataString);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		
		return true;
    }
    
    public boolean saveAs(){
    	JFileChooser file = new JFileChooser();
        FileFilter xmlFilter = new FileNameExtensionFilter("Fichiers XML", "xml");
               
        file.setFileFilter(xmlFilter);
        file.setDialogTitle("Save As");
        int result = file.showSaveDialog(this);

        if (result == JFileChooser.CANCEL_OPTION) {
        	return false;
        }else if (result == JFileChooser.APPROVE_OPTION) {
            fFile = file.getSelectedFile();
            if(fFile.exists()){
            	int response = JOptionPane.showConfirmDialog(null, "Overwrite existing file?",
            			"Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
                if(response == JOptionPane.CANCEL_OPTION){
                	return false;
                }
            }   
            
	        if(fFile.getPath().indexOf("xml")>0){
	        	boolean resp = writeFile(fFile, model.generateXMLProject());
	            if(resp){
	            	this.isSaved = true;
	            	this.setIsModified(false);
	            	return true;
	            }
	        }
        }
        
        return false;
    }
    
    public boolean importPPT(){
    	if(verifyProjectSaved()){
	    	//Import the PPT
	    	JFileChooser file = new JFileChooser();
		    FileFilter pptFilter = new FileNameExtensionFilter("Fichiers PPT(PowerPoint)","ppt");
		    file.setFileFilter(pptFilter);
		    file.setDialogTitle("Import ppt project");
		         
		    int result = file.showOpenDialog(this);
		    if (result == JFileChooser.CANCEL_OPTION) {
		        return false;
		    } else if (result == JFileChooser.APPROVE_OPTION) {
		        File f = file.getSelectedFile();
		        if(f.getAbsolutePath().indexOf("ppt")>0){
		        	FileInputStream is;
		        	try {
		        		is = new FileInputStream(f.getAbsolutePath());
						org.apache.poi.hslf.usermodel.SlideShow ppt = new org.apache.poi.hslf.usermodel.SlideShow(is);
						is.close();
						org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides();
						
						model=new ListSlideModel();
						model.setNbSlide(slide.length);
						model.setCurrentSlide(slide.length);
						model.setNameProject(f.getName());
						
						ArrayList<SlideContent> list=new ArrayList<SlideContent>();
						int cpt=1;
						for (org.apache.poi.hslf.model.Slide sl: slide){
							
							SlideContent s=new SlideContent();
							Color c = sl.getBackground().getFill().getBackgroundColor();
							
							s.setSlideBackgroundColor(c);
							s.setNumSlide(cpt);
							
							ArrayList<ElementSlide> elt=new ArrayList<ElementSlide>();
							TextRun[] textRuns = sl.getTextRuns();
							
							int i=0;
							for(Shape sh:sl.getShapes()){
															
								if(sh.getShapeName().equals("TextBox") || sh.getShapeType()==ShapeTypes.Rectangle){
								
									if(i>=textRuns.length)
										continue;
									
									TextElement te=new TextElement();
									System.out.println("Value of text = "+textRuns[i].getText());
									te.setTextValue(textRuns[i].getText());
									Rectangle r=sh.getAnchor();
									te.setPosX((int)r.getX());
									te.setPosY((int)r.getY());
									te.setHeight((int)r.getHeight());
									te.setWidth((int)r.getWidth());
									elt.add(te);
									TextRun tr=sl.getTextRuns()[0];
									//Font fnt=new Font(tr.getRichTextRuns()[0].getFontName(),0,tr.getRichTextRuns()[0].getFontSize());
									int type = 0;
									if(tr.getRichTextRuns()[0].isBold())
										type=Font.BOLD;
									 if(tr.getRichTextRuns()[0].isItalic())
										type+=Font.ITALIC;
									
								 //if(tr.getRichTextRuns()[0].is);
									Font fnt=new Font(tr.getRichTextRuns()[0].getFontName(),type,tr.getRichTextRuns()[0].getFontSize());
									System.out.println(type==Font.ITALIC);
									s.setSlideFont(fnt);
									s.setSlideFontColor(tr.getRichTextRuns()[0].getFontColor());
									te.setNumElement(i);
									
								}
								else if(sh.getShapeName().equals("PictureFrame")){
									System.out.println("immmmmmmmmmmmmmmmmmmmaaaaaaage");
									ImageElement ie=new ImageElement();
									Picture pic=(Picture) sh;
									PictureData pd=pic.getPictureData();
									byte[] data=pd.getData();
									int typ = pd.getType();
									File in = null;
									FileOutputStream out=null;
									try{
									 if (typ == Picture.JPEG){
										 	out=new FileOutputStream("slide0_"+cpt+"_"+(i+1)+".jpg");
										 	out.write(data);
										 	out.close();
							    	        in=new File("slide0_"+cpt+"_"+(i+1)+".jpg");
											System.out.println(in.getAbsolutePath());
							    	       
							    	      } else if (typ == Picture.PNG){
							    	        //FileInputStream in = null;
							    	    	  out=new FileOutputStream("slide0_"+cpt+"_"+(i+1)+".png");
											 	out.write(data);
											 	out.close();
							    	    	  in=new File("slide0_"+cpt+"_"+(i+1)+".png");
							    	    	  System.out.println(in.getAbsolutePath());
							    	      }
									}catch(Exception e){
										e.printStackTrace();
									}
							    	Rectangle r=sh.getAnchor();
							    	System.out.println("XXX:"+ie.getPosX());
							    	ie.setPosX((int)r.getX());
							    	System.out.println("XXX:"+ie.getPosX());
									ie.setPosY((int)r.getY());
							    	ie.setPath(in.getAbsolutePath());
									ie.setHeight((int)r.getHeight());
									ie.setWidth((int)r.getWidth());
									ie.setNumElement(i);
									ie.setPath(in.getAbsolutePath());
									elt.add(ie);
								}
								i++;
							}
							s.setListElements(elt);
							list.add(s);
							cpt++;
						}
						model.setListSlide(list);

					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				  setNewModel(model) ; 
				  return true;
				 }
			}
    	}
    	return false;
    }
		
    
    private boolean btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
    	return openNewProject();
    }
    
    public boolean exportPPT(){
    	JFileChooser file = new JFileChooser();
        FileFilter pptFilter = new FileNameExtensionFilter("Fichiers PowerPoint", "ppt");
               
        file.setFileFilter(pptFilter);
        file.setDialogTitle("Export to ppt");
        int result = file.showSaveDialog(this);

        if (result == JFileChooser.CANCEL_OPTION) {
        	return false;
        }else if (result == JFileChooser.APPROVE_OPTION) {
            File tmpFile = file.getSelectedFile();
            if(tmpFile.exists()){
            	int response = JOptionPane.showConfirmDialog(null, "Overwrite existing file?",
            			"Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
                if(response == JOptionPane.CANCEL_OPTION){
                	return false;
                }
            }   
            model.generatePPT(tmpFile);
            return true;
        }
        return false;
    }
    
    public void helpContents(){
    	HelpFrame helpContents = new HelpFrame("KDiapo Help Window","src/documentation/index.html");
    	helpContents.setVisible(true);
    }
    
    public void about(){
    	HelpFrame help = new HelpFrame("About KDiapo","src/documentation/about.html");
    	help.setVisible(true);
    }
    
    public void enableAllBtn(){
    	btnSave.setEnabled(true);
		btnSave.setEnabled(true);
        btnAddSlide.setEnabled(true);
        btnImage.setEnabled(true);
        btnText.setEnabled(true);
        btnVideo.setEnabled(true);
        btnBackground.setEnabled(true);
        btnFont.setEnabled(true);
        btnFontColor.setEnabled(true);
        menuSave.setEnabled(true);
        menuSaveAs.setEnabled(true);
        menuNewSlide.setEnabled(true);
        menuInsertText.setEnabled(true);
        exportToPPT.setEnabled(true);
        menuInsertImage.setEnabled(true);
        menuInsertVideo.setEnabled(true);
    }
    
    public void setLayoutForSlide(JPanel p){
    	
    	javax.swing.GroupLayout pSlideLayout = new javax.swing.GroupLayout(p);
		p.setLayout(pSlideLayout);
        pSlideLayout.setHorizontalGroup(
        		pSlideLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 800, Short.MAX_VALUE)
        );
        pSlideLayout.setVerticalGroup(
        	pSlideLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 600, Short.MAX_VALUE)
            );
    	
    	
    }
    /**-----------------------------------------------------------------------------------*/

    
    
    /**-----------------------------------------------------------------------------------*/
    /**Update View--------------------------------------------------------------------------*/
    /**-----------------------------------------------------------------------------------*/
	public void update(Observable arg0, Object arg1) {
		
		this.setIsModified(true);
		
		if(arg1 instanceof SlideContent){
			SlideContent sl = (SlideContent) arg1;
			System.out.println("oldSlide :: "+oldCurrentSlide+" New slide :: "+sl.getNumSlide());
			System.out.println("Slide updat� ou ajout�e : " + sl.getNameSlide());
			//-------------------------------------------------------------------------------
			
			//mise a jour tabbed pane pour gestuelle (pour l'instant on met une couleur noire ou blanche)
			/*if(sl.isHasImage())
				jPanel2.setBackground(Color.black);
			else
				jPanel2.setBackground(Color.white);
			if(sl.isHasVideo())
				jPanel3.setBackground(Color.black);
			else
				jPanel3.setBackground(Color.white);
			if(sl.isHasText())
				jPanel4.setBackground(Color.black);
			else
				jPanel4.setBackground(Color.white);*/
			//-------------------------------------------------------------------------------
			
			
			
			//mise a jour contentSlide (JPanel5)
			if(oldCurrentSlide!=sl.getNumSlide())//si changement de slide � la vue
			{
				//Mise � jour bordure current slide
				pContentDiapo.remove(currentSlide);
				
				currentSlide = new JPanel();
    			currentSlide.setBackground(model.getListSlide().get(model.getCurrentSlide()-1).getSlideBackgroundColor());
    			pContentDiapo.add(currentSlide);
    			currentSlide.setBounds(100,0,800,600);
    			//set Layout for insertion of elements
    			setLayoutForSlide(currentSlide);
    			
    			this.refreshSlide(sl,currentSlide);
    			
    			SnapShotView old = (SnapShotView) jPanel1.getComponent(oldCurrentSlide-1);
    			
    			System.out.println("Old nb slide="+oldNbSlide+" New="+model.getNbSlide());
    			  			
    				
    			old.setBorder(BorderFactory.createLineBorder(Color.white));
    			
    			
    			oldCurrentSlide = sl.getNumSlide();
    			
			}
			else {//Update screenshot if it's not the creation of the slide (it would mean that there isn't any components)
				
				if(jPanel1.getComponentCount()>0){

					SnapShotView old = (SnapShotView) jPanel1.getComponent(sl.getNumSlide()-1);
					old.updateSnapShot(currentSlide);

					jPanel1.revalidate();
					jPanel1.repaint();
					
				}
			}
			
		}
		else if(arg1 instanceof ListGesture){
			ListGesture lg = (ListGesture) arg1;
			JPanel p = null;
			if(lg.getType().equals("Video"))
				p = jPanel3;
			if(lg.getType().equals("Picture"))
				p = jPanel2;
			if(lg.getType().equals("Text"))
				p = jPanel4;
			
			for(int i=0;i<p.getComponentCount();i++){
				if(p.getComponent(i) instanceof GestureView){
					GestureView gv = (GestureView) p.getComponent(i);
					if(!lg.getListGest().get(gv.getNumGest()).isSelected()){
						
						gv.setBorder(BorderFactory.createLineBorder(Color.white));
						gv.setSelected(false);
					}
				}
			}
			
			p.revalidate();
			p.repaint();
		}
	}
	
	public void refreshSlide(SlideContent sl,JPanel p){
		Iterator<ElementSlide> itr = sl.getListElements().iterator();
	    while (itr.hasNext()) {
	    	ElementSlide element = itr.next();
	    	//s'l s'agit d'un texte
	    	if(element instanceof TextElement){
	    		
	    		TextElement elt = (TextElement) element;
	    		TextView area = new TextView(this,elt.getNumElement(),
	    				elt.getPosX(),elt.getPosY(),elt.getWidth(),elt.getHeight(),elt.getBackgroundColor(),
	            		model.getListSlide().get(model.getCurrentSlide()-1).getSlideFontColor(),
	            		model.getListSlide().get(model.getCurrentSlide()-1).getSlideFont());
	    		//on met le texte � jour
	    		area.setTextValue(elt.getTextValue());
	    		
	    		area.getResizer().repaint();
	    		
	    		//insertion of the element in the view
	    		p.add(area.getResizer(),elt.getNumElement());
	    		    
	    		p.revalidate();
	    		p.repaint();
	    	}
	    	
	    	if(element instanceof ImageElement){
	    		ImageElement elt = (ImageElement) element;
	    		ImageView area = new ImageView(this,elt.getNumElement(),elt.getPath(),elt.getPosX(),
	    				elt.getPosY(),elt.getWidth(),elt.getHeight());
	    	
	    			 	
	    		//insertion of the element in the view
	    		p.add(area.getResizer(),elt.getNumElement());
	    		    
	    		p.revalidate();
	    		p.repaint();
	    	}
	    	if(element instanceof VideoElement){
	    		VideoElement elt = (VideoElement) element;
	    		File f = new File(elt.getPath());
	    		
	    		VideoView area = new VideoView(this,elt.getNumElement(),f,elt.getPosX(),
	    				elt.getPosY(),elt.getWidth(),elt.getHeight());
	    	
	    		area.getResizer().repaint();
	    		
	    		//insertion of the element in the view
	    		p.add(area.getResizer(),elt.getNumElement());
	    		    
	    		p.revalidate();
	    		p.repaint();
	    	}
	    }
	}
	
	//Remove an element from the current slide
	public void removeElement(int num){
		//We remove the element num
		currentSlide.remove(num);
		currentSlide.revalidate();
		
		for(int i=0;i<currentSlide.getComponentCount();i++){
			
			if(i>=num){ // We decrease number of element > num
				Resizable r = (Resizable)currentSlide.getComponent(i);
				ElementView elt = (ElementView) r.getResizedElement();
				elt.setNumElement(elt.getNumElement()-1);
			}
		}
		
		currentSlide.revalidate();
		currentSlide.repaint();
	}
	
	//Remove a slide
	public void removeSlide(int num,int currentNum){
		
		jPanel1.remove(num-1);
		
		//System.out.println("\nNEW current num="+currentNum+" (OLD="+oldCurrentSlide);
		
		for(int i=0;i<jPanel1.getComponentCount();i++){
			SnapShotView sp2 = (SnapShotView) jPanel1.getComponent(i);
			if(i>=num-1){
				
				//jPanel1.remove(i);
				System.out.println("\tSlide where number is decrease : (num "+sp2.getNumSlide());
				sp2.setNumSlide(i+1);
				
				//jPanel1.add(sp2,i);
				/*JFrame f = new JFrame();
				f.setSize(300,300);
				f.add(sp2);
				f.*/
			}
			System.out.println("\t\tCurrentNum="+currentNum+" et i="+i);
			if(i==currentNum-1)
				sp2.setBorder(BorderFactory.createLineBorder(Color.red));
				
		}
	
		pContentDiapo.remove(currentSlide);
		
		currentSlide = new JPanel();
		currentSlide.setBackground(model.getListSlide().get(model.getCurrentSlide()-1).getSlideBackgroundColor());
		pContentDiapo.add(currentSlide);
		currentSlide.setBounds(100,0,800,600);
		//set Layout for insertion of elements
		setLayoutForSlide(currentSlide);
		this.refreshSlide(model.getListSlide().get(model.getCurrentSlide()-1),currentSlide);
		
		oldCurrentSlide=model.getNbSlide();
		
		jPanel1.revalidate();
		jPanel1.repaint();
	}
	/**-----------------------------------------------------------------------------------*/
	/**-----------------------------------------------------------------------------------*/
	
	
	
	/**-----------------------------------------------------------------------------------*/
	/**Getter and Setter------------------------------------------------------------------*/
	/**-----------------------------------------------------------------------------------*/
	public ListSlideModel getModel(){
		return this.model;
	}
	
	public JPanel getCurrentSlide() {
		return currentSlide;
	}
	public void setCurrentSlide(JPanel currentSlide) {
		this.currentSlide = currentSlide;
	}
	public void setIsModified(boolean b){
		isModified = b;
		if(isModified){
			this.setTitle(model.getNameProject() + "  (modified)");
		}
		else
			this.setTitle(model.getNameProject());
	}
	public void setNewModel(ListSlideModel md){
		this.model = md;
		printModel();
		
		oldCurrentSlide=md.getNbSlide();
		oldNbSlide=md.getNbSlide();
		
		//Update View--------------------------------------------------
		this.enableAllBtn();
		
		//Creation of current Slide
		pContentDiapo.removeAll();
		currentSlide = new JPanel();
		currentSlide.setBackground(model.getListSlide().get(model.getCurrentSlide()-1).getSlideBackgroundColor());
		pContentDiapo.add(currentSlide);
		currentSlide.setBounds(100,0,800,580);
		
		//set Layout for insertion of elements
		setLayoutForSlide(currentSlide);
		
		//set title to application
		this.setTitle(md.getNameProject());
		
		//We refresh the current slide to display the components
		this.refreshSlide(model.getListSlide().get(model.getCurrentSlide()-1),currentSlide);
		
		//empty the jPanel1
		jPanel1.removeAll();
		
		//We create all panel for each slide to be able to have a screenshot
		for(int i=0;i<md.getNbSlide();i++){
			JPanel p = new JPanel();
			p.setBounds(100,0,800,580);
			p.setBackground(model.getListSlide().get(model.getCurrentSlide()-(model.getNbSlide()-i)).getSlideBackgroundColor());
			//System.out.println("Size "+p.getSize().width+"//"+p.getSize().height);
			
			setLayoutForSlide(p);
			
			refreshSlide(md.getListSlide().get(i), p);
			
			
			//Creation of snapeshot
			SnapShotView sp = new SnapShotView(this, i+1, p);
			sp.updateSnapShot(p);
			
			
			//if it isn't the current slide (default current slide is the last), color border is white
			if(i<md.getNbSlide()-1)
				sp.setBorder(BorderFactory.createLineBorder(Color.white));
			
			//jPanel1.add(sp,i);
			jPanel1.add(sp);
			
		}
		
		
		jPanel1.revalidate();
		jPanel1.repaint();
		
		
		prepareChoiceGest(jPanel2,"Picture");
    	prepareChoiceGest(jPanel3,"Video");
    	prepareChoiceGest(jPanel4,"Text");
    	
		
		
		this.model.addObserver(this);
		
		
	}
	
	/**-----------------------------------------------------------------------------------*/


	/**-----------------------------------------------------------------------------------*/
	/**Debug----------------------------------------------------------------------*/
	/**-----------------------------------------------------------------------------------*/
	
	//Ecrire Contenu du mod�le
	public void printModel(){
			
		System.out.println("Nb slides : "+model.getNbSlide());
		System.out.println("Nom projet : "+model.getNameProject());
		System.out.println("Parcours de chaque slide : ");
		Iterator<SlideContent> itr = model.getListSlide().iterator();
		int i=0;
		while (itr.hasNext()) {
			i++;
			SlideContent slide = itr.next();
			System.out.println("\tSlide "+slide.getNumSlide());
			System.out.println("\tName : "+slide.getNameSlide());
			System.out.println("\tNb elements : "+slide.getNbElements());
			    
			System.out.println("\tParcours des �l�ments de la slide : ");
			Iterator<ElementSlide> itr2 = model.getListSlide().get(i-1).getListElements().iterator();
			while (itr2.hasNext()) {
			    //marchera que si c'est un texte pour le moment
				ElementSlide element = itr2.next();
				if(element instanceof TextElement){
					TextElement elt = (TextElement) element;
					System.out.println("\t\tnum="+elt.getNumElement()+" Texte :"+elt.getTextValue());
					System.out.println("\t\tposX="+elt.getPosX()+" posY="+elt.getPosY() +" width:"+elt.getWidth()+" height"+elt.getHeight());
				}
				if(element instanceof ImageElement){
					ImageElement elt = (ImageElement) element;
					System.out.println("\t\tImage :"+elt.getPath());
				}
				
			}
		}
	}
	/**-----------------------------------------------------------------------------------*/
	/**Menu Listeners----------------------------------------------------------------------*/
	/**-----------------------------------------------------------------------------------*/
	
	// Menu events
    class Action implements ActionListener {
          public void actionPerformed(ActionEvent e) {

                // We get the source
        	  JMenuItem source = (JMenuItem)(e.getSource());
              // For each option we have a different processing 
              if(source.getText() == "SlideShow")
              	goIntoPresentationMode();
              if(source.getText() == "New project")
              	openNewProject();
              if(source.getText() == "Open an existing project")
              	openExistingProject();
              if(source.getText() == "Save")
              	save();
              if(source.getText() == "Save as")
              	saveAs();
              if(source.getText() == "Export to ppt")
                exportPPT();
              if(source.getText() == "Import ppt file")
                importPPT();
              if(source.getText() == "New slide")
              	newSlide();
              if(source.getText() == "Insert text")
              	insertText();
              if(source.getText() == "Insert an image")
              	insertImage();
              if(source.getText() == "Insert a video")
              	insertVideo();                
              if(source.getText() == "Help contents")
              	helpContents();
              if(source.getText() == "About")
              	about();
                
                
          }
    }
    
    // Full Screen Presentation
    void goIntoPresentationMode(){
        System.out.println("Slide Show !! ");
        slideShowFrame = SlideShow.getInstance(model);
        slideShowFrame.setVisible(true);
        Runtime runtime = Runtime.getRuntime();
        try {
        	// working if the resource is placed in the same folder, would be nice to be improved 
        	// so that it works directly with the resource KDiapoProcessing (shell script)
            //System.out.println(Main.class.getResource("/K_diapo").getPath());
        	if (isUnix()) {
        		String str = Main.class.getResource("/K_diapo").toString();
        		// a bit tricky, for now the application.linux folder 
        		// has to be placed in the same folder as the generated executable .jar
	            str = str.split(":")[str.split(":").length-1];
	            String res = "";
	            if (str.indexOf("!") > 0){
	                //System.out.println("in if/for");
	                str = str.split("!")[0];
	                for (int i = 0; i < str.split("/").length-1; i++){
	                    res += str.split("/")[i]+"/";
	                }
	                res += "application.linux/K_diapo";    
		            str = res;
	            }
	            System.out.println(str);
	            File f = new File(str);
	            
	         	if ( f.exists() ) {
	         		runtime.exec(str);
	         	}
	         	else 
	         		JOptionPane.showMessageDialog(null,"Kinect application not found, you can use keyboard");
        	}
        	else {
        		JOptionPane.showMessageDialog(null,"OS not supported for Kinect use, you can use keyboard");
        	}
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    private static boolean isUnix(){    	 
		String os = System.getProperty("os.name").toLowerCase();
		//linux or unix
	    return (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0); 
	}
    
	/**-----------------------------------------------------------------------------------*/
	/**Main ------------------------------------------------------------------------------*/
	/**-----------------------------------------------------------------------------------*/
	public static void main(String args[]) {
		 JFrame.setDefaultLookAndFeelDecorated(true);
         SwingUtilities.invokeLater(new Runnable() {
                 public void run() {    
                	   try {
                     	  UIManager.setLookAndFeel(new com.lipstikLF.LipstikLookAndFeel());
                       } catch (Exception e) {
                                  // handle exception
                              }
                  new CreationFrame().setVisible(true);
                 }
         }); 
		 
		 //new CreationFrame().setVisible(true);
		 
	}
	/**-----------------------------------------------------------------------------------*/
	/**-----------------------------------------------------------------------------------*/
		
		

}
